import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/layout'
import Detail from '@/views/detail'
import Login from '@/views/login'
import Register from '@/views/register'
import Article from '@/views/article'
import Collect from '@/views/collect'
import Like from '@/views/like'
import User from '@/views/user'
import { getToken } from '@/utils/storage'
Vue.use(VueRouter)

const routes = [
  // 一级路由配置
  // 首屏
  {
    path: '/',
    component: Layout,
    // 重定向
    redirect: '/article',
    // 二级路由：面经+收藏+喜欢+我的
    children: [
      { path: '/article', component: Article },
      { path: '/collect', component: Collect },
      { path: '/like', component: Like },
      { path: '/user', component: User }
    ]
  },
  // 详情
  { path: '/detail/:id', component: Detail },
  // 登录
  { path: '/login', component: Login },
  // 注册
  { path: '/register', component: Register }
]

const router = new VueRouter({
  routes
})
// 白名单
const whiteList = ['/login', '/register']
// 全局前置守卫：在路由跳转之前，页面渲染之前，被自动调用并在路由导出前配置好
// to：要去到哪里
// from：路由从哪里来
// next：放行
router.beforeEach((to, from, next) => {
  // console.log('路由要去哪里', to)
  // console.log('路由从哪里来', from)
  // next()
  const token = getToken()
  if (token) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
